<template>
  <div class="sort">
    <Row :gutter="18">
      <i-col span="5">
        <Menu :style="{width: '100%'}" active-name="0" @on-select="select">
          <MenuItem v-for="(item, index) in categoriesList" :key="item.id" :name="index">{{item.name}}</MenuItem>
        </Menu>
      </i-col>
      <i-col span="19">
        <Row>
          <i-col span="8">
            <!--头像上传-->
            <Upload
                    ref="upload"
                    :show-upload-list="false"
                    :format="['jpg','jpeg','png']"
                    :max-size="2048"
                    type="drag"
                    :on-success="updateImageSuccess"
                    :on-error="updateImageError"
                    :data="{
                      categoryId: categoryId
                    }"
                    :action="updateImage"
                    style="display: inline-block;width:200px;">
              <Avatar :src="categoriesImage" size="200"></Avatar>
            </Upload>
          </i-col>
          <!--头像上传-->
          <!--分类信息编辑-->
          <i-col span="10">
            <Form ref="classification" :model="classification" :rules="ruleCustom" :label-width="80">
              <FormItem prop="name">
                <i-input v-model="classification.name" :readonly="!isEdit" size="large" placeholder="分类名" style="width: 300px" />
              </FormItem>
              <FormItem  prop="describe">
                <i-input v-model="classification.describe" :readonly="!isEdit" :style="{marginTop: '15px', backgroundColor: '#fff'}" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="分类描述" />
              </FormItem>
            </Form>

          </i-col>
          <!--分类信息编辑-->
          <i-col span="6" :style="{textAlign: 'center'}">
            <Tooltip content="是否开启编辑信息！" placement="top">
              <i-switch size="large" :before-change="changeEdit">
                <span slot="open">开启</span>
                <span slot="close">关闭</span>
              </i-switch>
            </Tooltip>
            <br/>

            <Button v-show="isEdit" :loading="loading" @click="confirm" style="margin-top: 15px" type="primary" shape="circle">
              <span v-if="!loading">确认修改</span>
              <span v-else>修改中。。。。</span>
            </Button>
            <br/>
            <Button :loading="addLoading" @click="addShow" icon="ios-add-circle-outline" style="margin-top: 15px" type="info" shape="circle">
              <span v-if="!addLoading">增加分类</span>
              <span v-else>增加中。。。。</span>
            </Button>
          </i-col>
        </Row>
        <Divider :style="{color: '#3399FF'}">{{articleLength}}篇文章</Divider>

        <!--分类中的文章-->
        <div :style="{ width: '80%'}">
          <List>
            <ListItem v-for="(item, index) in articleList" :key="index">
              <ListItemMeta avatar="http://dd.ddandang.top/blog/images/images.jpg" :title="item.title" :description="item.description" />
              <template slot="action">
                <li>
                  <a @click="remove(item.id)">移除</a>
                </li>
              </template>
            </ListItem>
          </List>
        </div>
      </i-col>
    </Row>

    <!--增加分类-->
    <Drawer
            title="增加分类"
            v-model="isShow"
            width="300"
            :mask-closable="false"
            :closable="false"
            :styles="{textAlign: 'center'}"
    >
      <Tooltip :style="{marginTop: '30px',marginBottom: '20px'}" content="是否上传图片！" placement="top">
        <i-switch size="large" :before-change="changeUpload">
          <span slot="open">上传</span>
          <span slot="close">取消</span>
        </i-switch>
      </Tooltip>

      <Form ref="addInfo" :model="addInfo" :rules="ruleCustom">
        <FormItem prop="name">
          <i-input v-model="addInfo.name"  clearable size="large" placeholder="分类名"/>
        </FormItem>
        <FormItem  prop="describe">
          <i-input v-model="addInfo.describe"  :style="{marginTop: '15px', backgroundColor: '#fff'}" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="分类描述" />
        </FormItem>
      </Form>

      <Upload
              :on-error="handleError"
              :on-success="handleSuccess"
              :disabled="!(nameRight&&describeRight)"
              v-show="isUpload"
              ref="upload"
              :show-upload-list="false"
              :format="['jpg','jpeg','png']"
              :max-size="2048"
              type="drag"
              :data="{
                name: addInfo.name,
                description: addInfo.describe
              }"
              :action="insertUrl"
              style="display: inline-block;width:150px;margin-bottom: 20px">
        <Avatar src="http://dd.ddandang.top/blog/images/images.jpg" size="150"></Avatar>
      </Upload>
      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" @click="cancel">取消</Button>
        <Button v-show="!isUpload" type="primary" @click="insert">提交</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
  import {
    insertCategories,
    insertUrl,
    updateImage,
    updateCategory,
    allCategories,
    listClassificationVoByCategoryId,
    removeArticleCategory
  } from "@/network/classification";

  export default {
    name: "Sort",
    data() {
      const validateName = (rule, value, callback) => {
        if (value === '') {
          this.nameRight = false;
          callback(new Error('分类名不能为空！'));
        } else if (value.length > 20) {
          this.nameRight = false;
          callback(new Error('分类名字数不能大于20'));
        } else {
          this.nameRight = true;
          callback();
        }
      };
      const validateDescribe = (rule, value, callback) => {
        if (value === '') {
          this.describeRight = false;
          callback(new Error('分类描述不能为空！'));
        } else if (value.length > 100) {
          this.describeRight = false;
          callback(new Error('分类描述字数不能大于100'));
        } else {
          this.describeRight = true;
          callback();
        }
      };
      return {
        //分类列表
        categoriesList: [],
        categoriesIndex: 0,
        //分类图片
        categoriesImage: '',
        //分类名
        categoriesName: '',
        //分类描述
        categoriesDescription: '',
        //分类Id
        categoryId: 0,
        //该分类的文章
        articleList: [],
        //文章数量
        articleLength: 0,
        updateImage: updateImage,
        insertUrl: insertUrl,
        //提示框
        isMessage: true,
        nameRight: false,
        describeRight: false,
        //是否上传图片 上传图片时同时将其他信息一起上传
        isUpload: false,
        loading: false,
        addLoading: false,
        isEdit: false,
        //增加分类的抽屉显示
        isShow: false,
        classification: {
          name: '',
          describe: ''
        },
        addInfo: {
          name: '',
          describe: ''
        },
        ruleCustom: {
          name: [
            { validator: validateName, trigger: 'blur' }
          ],
          describe: [
            { validator: validateDescribe, trigger: 'blur' }
          ]
        }
      }
    },
    mounted() {
      //获取分类列表
      this.listCategories();
    },
    methods: {
      changeEdit() {
        this.classification.name = this.categoriesName;
        this.classification.describe = this.categoriesDescription;
        this.isEdit = !this.isEdit;
      },
      changeUpload() {
        if(this.isMessage) {
          this.$Notice.info({
            title: '友善提示！',
            desc: '开启图片上传之后其他参数将和图片一同上传！'
          });
          this.isMessage = false;
        }

        this.isUpload = !this.isUpload;
      },
      confirm() {
        this.$refs['classification'].validate((valid) => {

          if (valid) {
            this.loading = true;

            this.loading = false;
            updateCategory(this.categoryId, this.classification.name, this.classification.describe)
            .then(res => {
              if(res.code === 2000) {
                this.$Message.success('更新分类信息成功!');
                //同步信息
                this.categoriesName = this.classification.name
                this.categoriesDescription = this.classification.describe;
                this.categoriesList[this.categoriesIndex].name = this.classification.name;
                this.categoriesList[this.categoriesIndex].description = this.classification.describe;
                this.isEdit = !this.isEdit;
              }
            }).catch( err => {
              err.log(err);
            })

          } else {
            this.$Message.error('请按要求填写信息!');
          }
        })
      },
      //增加分类的框显示
      addShow() {
        this.addLoading = !this.addLoading;
        this.isShow = !this.isShow;
      },
      cancel() {
        this.isMessage = true;
        this.describeRight = false;
        this.nameRight = false;
        this.addLoading = !this.addLoading;
        this.isShow = !this.isShow;
        this.$refs['addInfo'].resetFields();
      },
      remove(articleId) {
        this.$Modal.confirm({
          title: '移除文章',
          content: '<p>确认将此文章从分类中移除？</p>',
          onOk: () => {
            removeArticleCategory(articleId, this.categoryId).then(res => {
              if(res.code === 2000) {
                this.listClassificationVoByCategoryId();
                this.$Message.success('移除成功！文章已进入未分类！');
              }else {
                this.$Message.error('移除失败！');
              }
            }).catch(() => {
              this.$Message.error('移除失败！');
            })
          },
          onCancel: () => {
          }
        });
      },
      //增加分类
      insert() {
        this.$refs['addInfo'].validate((valid) => {
          if (valid) {
            insertCategories(this.addInfo.name, this.addInfo.describe).then( res => {
              if(res.code === 2000) {
                this.addLoading = !this.addLoading;
                this.isShow = !this.isShow;
                this.$Message.success('增加分类成功！');
                this.$refs['addInfo'].resetFields();
              }
            }).catch( () => {
            })

          } else {
            this.$Message.error('请按要求填写信息!');
          }
        })
      },
      //增加分类上传图片成功
      handleSuccess () {
        this.addLoading = !this.addLoading;
        this.isShow = !this.isShow;
        this.$Message.success('增加分类成功！');
        this.$refs['addInfo'].resetFields();
      },
      //增加分类上传图片失败
      handleError(error) {
        this.$Message.error('增加分类失败！'+error);
      },
      //更新图片成功
      updateImageSuccess(response) {
        this.categoriesImage = response.data.imageUrl;
      },
      updateImageError() {
        this.$Message.error('更新图片失败！');
      },
      //获取分类列表
      listCategories() {
        allCategories().then( res => {
          this.categoriesList = res.data.categoriesList;
          this.select(0);

        }).catch( () => {
        })
      },

      //选择分类
      select(name) {
        this.categoriesIndex = name;
        this.classification.name = this.categoriesList[name].name;
        this.classification.describe = this.categoriesList[name].description;
        this.categoryId = this.categoriesList[name].id;
        this.categoriesName = this.categoriesList[name].name;
        this.categoriesDescription = this.categoriesList[name].description;
        if(this.categoriesList[name].image === ''|| this.categoriesList[name].image === null) {
          this.categoriesImage = 'http://dd.ddandang.top/blog/images/noImage.png';
        }else {
          this.categoriesImage = this.categoriesList[name].image;
        }
        //获取文章
        this.listClassificationVoByCategoryId();
      },
      listClassificationVoByCategoryId() {
        listClassificationVoByCategoryId(this.categoryId).then(res => {
          this.articleList = res.data.listClassification;
          this.articleLength = res.data.listClassification.length;
        }).catch(() => {
        })
      }
    }
  }
</script>

<style scoped>

</style>